window.Guyu = {};
(function (Guyu) {
    class Handler {
        constructor(caller = null, method = null, args = null, once = false) {
            this.once = false;
            this.caller = null;
            this.method = null;
            this.args = null;
            this._id = 0;
            this.setTo(caller, method, args, once);
        }
        setTo(caller, method, args, once = false) {
            this._id = Handler._gid++;
            this.caller = caller;
            this.method = method;
            this.args = args;
            this.once = once;
            return this;
        }
        run() {
            if (this.method == null)
                return null;
            const id = this._id;
            const result = this.method.apply(this.caller, this.args);
            this._id === id && this.once && this.recover();
            return result;
        }
        runWith(data) {
            if (this.method == null)
                return null;
            const id = this._id;
            let result;
            if (data == null)
                result = this.method.apply(this.caller, this.args);
            else if (!this.args && !data.unshift)
                result = this.method.call(this.caller, data);
            else if (this.args)
                result = this.method.apply(this.caller, this.args.concat(data));
            else
                result = this.method.apply(this.caller, data);
            this._id === id && this.once && this.recover();
            return result;
        }
        clear() {
            this.caller = null;
            this.method = null;
            this.args = null;
            return this;
        }
        recover() {
            if (this._id > 0) {
                this._id = 0;
                Handler._pool.push(this.clear());
            }
        }
        static create(caller, method, args = null, once = true) {
            if (Handler._pool.length)
                return Handler._pool.pop().setTo(caller, method, args, once);
            return new Handler(caller, method, args, once);
        }
    }
    Handler._pool = [];
    Handler._gid = 1;
    class EventHandler extends Handler {
        constructor(caller, method, args, once) {
            super(caller, method, args, once);
        }
        recover() {
            if (this._id > 0) {
                this._id = 0;
                EventHandler._pool.push(this.clear());
            }
        }
        static create(caller, method, args = null, once = true) {
            if (EventHandler._pool.length)
                return EventHandler._pool.pop().setTo(caller, method, args, once);
            return new EventHandler(caller, method, args, once);
        }
    }
    EventHandler._pool = [];
    class EventDispatcher {
        constructor() {
            this._events = new Map();
        }
        hasListener(type) {
            return this._events.has(type) && this._events.get(type).length > 0;
        }
        event(type, data = null) {
            if (!this._events.has(type))
                return false;
            const handlers = this._events.get(type).slice();
            for (let i = 0; i < handlers.length; i++) {
                const handler = handlers[i];
                if (handler) {
                    data != null ? handler.runWith(data) : handler.run();
                    if (handler.once) {
                        const index = this._events.get(type).indexOf(handler);
                        if (index > -1) {
                            this._events.get(type).splice(index, 1);
                            handler.recover();
                        }
                    }
                }
            }
            if (this._events.get(type).length === 0) {
                this._events.delete(type);
            }
            return true;
        }
        on(type, caller, listener, args = null) {
            return this._createListener(type, caller, listener, args, false);
        }
        once(type, caller, listener, args = null) {
            return this._createListener(type, caller, listener, args, true);
        }
        _createListener(type, caller, listener, args, once) {
            if (!this._events.has(type)) {
                this._events.set(type, []);
            }
            const handler = EventHandler.create(caller, listener, args, once);
            this._events.get(type).push(handler);
            return this;
        }
        off(type, caller, listener, onceOnly = false) {
            if (!this._events.has(type))
                return this;
            const handlers = this._events.get(type);
            for (let i = handlers.length - 1; i >= 0; i--) {
                const handler = handlers[i];
                if (handler &&
                    (!caller || handler.caller === caller) &&
                    (!listener || handler.method === listener) &&
                    (!onceOnly || handler.once)) {
                    handlers.splice(i, 1);
                    handler.recover();
                }
            }
            if (handlers.length === 0) {
                this._events.delete(type);
            }
            return this;
        }
        offAll(type = null) {
            if (type) {
                if (this._events.has(type)) {
                    const handlers = this._events.get(type);
                    for (const handler of handlers) {
                        handler.recover();
                    }
                    this._events.delete(type);
                }
            }
            else {
                //@ts-ignore
                for (const [_, handlers] of this._events) {
                    for (const handler of handlers) {
                        handler.recover();
                    }
                }
                this._events.clear();
            }
            return this;
        }
        offAllCaller(caller) {
            if (!caller)
                return this;
            //@ts-ignore
            for (const [type, handlers] of this._events) {
                for (let i = handlers.length - 1; i >= 0; i--) {
                    const handler = handlers[i];
                    if (handler && handler.caller === caller) {
                        handlers.splice(i, 1);
                        handler.recover();
                    }
                }
                if (handlers.length === 0) {
                    this._events.delete(type);
                }
            }
            return this;
        }
        isMouseEvent(type) {
            return EventDispatcher.MOUSE_EVENTS[type] || false;
        }
    }
    EventDispatcher.MOUSE_EVENTS = {
        "rightmousedown": true,
        "rightmouseup": true,
        "rightclick": true,
        "mousedown": true,
        "mouseup": true,
        "mousemove": true,
        "mouseover": true,
        "mouseout": true,
        "click": true,
        "doubleclick": true
    };
    Guyu.EventDispatcher = EventDispatcher;
    Guyu.dispatcher = new EventDispatcher();
})(Guyu);

(function (Guyu) {
    /**
     * 通用本地存储类
     * 提供跨平台的本地存储功能，不依赖特定游戏引擎
     */
    class Storage {
        constructor(prefix = '') {
            this._isAvailable = false;
            this._prefix = 'GuyuDb.';
            if (prefix) {
                this._prefix = prefix;
            }
            this._checkAvailability();
        }
        /**
         * 获取单例实例
         */
        static getInstance(prefix = '') {
            if (!this._instance) {
                this._instance = new Storage(prefix);
            }
            else if (prefix && this._instance._prefix !== prefix) {
                Guyu.Log.warn('存储实例已存在，无法更改前缀');
            }
            return this._instance;
        }
        /**
         * 检查本地存储是否可用
         */
        _checkAvailability() {
            try {
                if (typeof localStorage === 'undefined') {
                    this._isAvailable = false;
                    return;
                }
                // 测试存储功能
                this.localStorage.setItem('test', 'test');
                this.localStorage.removeItem('test');
                this._isAvailable = true;
            }
            catch (e) {
                this._isAvailable = false;
                Guyu.Log.warn('本地存储不可用', e);
            }
        }
        get localStorage() {
            let cc = window["cc"];
            if (cc && cc.sys && cc.sys.localStorage) {
                return cc.sys.localStorage;
            }
            return window.localStorage;
        }
        /**
         * 判断本地存储是否可用
         */
        isAvailable() {
            return this._isAvailable;
        }
        /**
         * 存储字符串数据
         * @param key 键名
         * @param value 要存储的字符串值
         * @returns 是否存储成功
         */
        set(key, value) {
            if (!this._isAvailable)
                return false;
            try {
                const prefixedKey = this._prefix + key;
                this.localStorage.setItem(prefixedKey, value);
                return true;
            }
            catch (e) {
                Guyu.Log.error('存储数据失败', e);
                return false;
            }
        }
        /**
         * 获取字符串数据
         * @param key 键名
         * @param defaultValue 默认值（当获取失败时返回）
         * @returns 存储的字符串值或默认值
         */
        get(key, defaultValue = '') {
            if (!this._isAvailable)
                return defaultValue;
            try {
                const prefixedKey = this._prefix + key;
                const data = this.localStorage.getItem(prefixedKey);
                return data || defaultValue;
            }
            catch (e) {
                Guyu.Log.error('获取数据失败', e);
                return defaultValue;
            }
        }
        /**
         * 删除数据
         * @param key 键名
         * @returns 是否删除成功
         */
        remove(key) {
            if (!this._isAvailable)
                return false;
            try {
                const prefixedKey = this._prefix + key;
                this.localStorage.removeItem(prefixedKey);
                return true;
            }
            catch (e) {
                Guyu.Log.error('删除数据失败', e);
                return false;
            }
        }
        /**
         * 清空所有数据
         * @returns 是否清空成功
         */
        clear() {
            if (!this._isAvailable)
                return false;
            try {
                this.localStorage.clear();
                return true;
            }
            catch (e) {
                Guyu.Log.error('清空数据失败', e);
                return false;
            }
        }
        /**
         * 获取所有键名
         * @returns 键名数组
         */
        keys() {
            if (!this._isAvailable)
                return [];
            try {
                const keys = [];
                for (let i = 0; i < this.localStorage.length; i++) {
                    const key = this.localStorage.key(i);
                    if (key !== null && key.startsWith(this._prefix)) {
                        keys.push(key.slice(this._prefix.length));
                    }
                }
                return keys;
            }
            catch (e) {
                Guyu.Log.error('获取键名失败', e);
                return [];
            }
        }
        /**
         * 判断是否存在某个键
         * @param key 键名
         * @returns 是否存在
         */
        has(key) {
            if (!this._isAvailable)
                return false;
            const prefixedKey = this._prefix + key;
            return this.localStorage.getItem(prefixedKey) !== null;
        }
    }
    Storage._instance = null;
    Guyu.Storage = Storage;
    Guyu.storage = Storage.getInstance();
})(Guyu);

(function (Guyu) {
    class AdapterManager {
        static get isMiniGamePlatform() {
            return this.detectPlatform() !== null;
        }
        static detectPlatform() {
            //@ts-ignore
            if (typeof KSGameGlobal !== 'undefined')
                return 'KS';
            //@ts-ignore
            if (typeof wx !== 'undefined')
                return 'WX';
            return null;
        }
        static get adapter() {
            if (!this.currentAdapter) {
                const platform = this.detectPlatform();
                if (platform) {
                    this.currentAdapter = this.platformAdapters[platform]();
                }
                else {
                    this.currentAdapter = new Guyu.DefaultAdapter();
                }
            }
            return this.currentAdapter;
        }
        static hideLoading() {
            this.adapter.ui.hideLoading();
        }
        static showLoading(msg) {
            this.adapter.ui.showLoading(msg);
        }
        static showToast(msg) {
            this.adapter.ui.showToast(msg);
        }
        static showAlert(msg) {
            this.adapter.ui.showAlert(msg);
        }
    }
    AdapterManager.currentAdapter = null;
    AdapterManager.platformAdapters = {
        KS: () => new Guyu.KSAdapter(),
        WX: () => new Guyu.WXAdapter()
    };
    Guyu.AdapterManager = AdapterManager;
})(Guyu);

(function (Guyu) {
    class DefaultAdapter {
        constructor() {
            this.wx = null;
            this.onMe = false;
            this.appId = null;
            this.ad = {
                init() {
                },
                playAd: function (opt) {
                    return Promise.resolve({
                        success: true
                    });
                }
            };
            this.ui = {
                platObj: null,
                showToast(msg) {
                    Guyu.Log.debug("showToast msg:" + msg);
                },
                showAlert(msg) {
                    if (alert) {
                        alert(msg);
                    }
                },
                showLoading(msg) {
                    Guyu.Log.debug("showLoading msg:" + msg);
                },
                hideLoading() {
                }
            };
        }
    }
    Guyu.DefaultAdapter = DefaultAdapter;
})(Guyu);

(function (Guyu) {
    class RuntimeSDK {
        static get onH5() {
            if (this.onMiniGame) {
                return false;
            }
            try {
                // 基础环境检查
                if (typeof window === 'undefined' ||
                    typeof window.document === 'undefined' ||
                    typeof window.navigator === 'undefined' ||
                    typeof window['eval'] !== 'function') {
                    return false;
                }
                // DOM功能性检查
                const testDiv = window.document.createElement('div');
                if (!testDiv || typeof testDiv.appendChild !== 'function') {
                    return false;
                }
                // 浏览器API检查
                if (!window.navigator.userAgent ||
                    typeof window.addEventListener !== 'function') {
                    return false;
                }
                return true;
            }
            catch (e) {
                return false;
            }
        }
        static get onMiniGame() {
            let res = this.onWXMiniGame || this.onKSMiniGame || this.onAliMiniGame || this.onTTMiniGame;
            return res;
        }
        static get onWXMiniGame() {
            //@ts-ignore
            return typeof wx !== 'undefined';
        }
        static get onKSMiniGame() {
            //@ts-ignore
            return typeof KSGameGlobal !== 'undefined';
        }
        static get onAliMiniGame() {
            //@ts-ignore
            return typeof my !== 'undefined';
        }
        static get onTTMiniGame() {
            //@ts-ignore
            return typeof tt !== 'undefined';
        }
        static get runtimeName() {
            if (this.onH5) {
                return 'h5';
            }
            else if (this.onMiniGame) {
                if (this.onWXMiniGame) {
                    return 'wx';
                }
                else if (this.onKSMiniGame) {
                    return 'ks';
                }
                else if (this.onAliMiniGame) {
                    return 'my';
                }
                else if (this.onTTMiniGame) {
                    return 'tt';
                }
                return 'minigame';
            }
            else {
                return 'unknown';
            }
        }
    }
    Guyu.RuntimeSDK = RuntimeSDK;
})(Guyu);

(function (Guyu) {
    class AdFactory {
        static get ClsAdapter() {
            if (Guyu.RuntimeSDK.onKSMiniGame) {
                return Guyu.KSADAdapeter;
            }
            if (Guyu.RuntimeSDK.onWXMiniGame) {
                return Guyu.WXAdAdapter;
            }
            return null;
        }
        static getAD(opt) {
            const { adUnitId, init = false } = opt;
            let inst = this.adMap.get(adUnitId);
            if (inst) {
                return inst;
            }
            inst = new AdFactory.ClsAdapter();
            this.adMap.set(adUnitId, inst);
            if (init) {
                inst.init({ adUnitId });
            }
            return inst;
        }
        static removeAd(adUnitId, destroy = true) {
            let inst = this.adMap.get(adUnitId);
            if (!inst)
                return false;
            if (destroy) {
                inst.destroy();
            }
            this.adMap.delete(adUnitId);
            return true;
        }
        /**
         * 获取原生模板广告实例
         * @param opt 广告配置选项
         * @returns 原生模板广告实例
         */
        static getCustomAd(opt) {
            const { adUnitId } = opt;
            if (!adUnitId) {
                console.warn("adUnitId is required 原生模板广告实例获取失败");
                return null;
            }
            let inst = this.customAdMap.get(adUnitId);
            if (inst) {
                return inst;
            }
            inst = new Guyu.WXCustomAd();
            this.customAdMap.set(adUnitId, inst);
            inst.init(opt);
            return inst;
        }
        /**
         * 移除原生模板广告
         * @param adUnitId 广告单元ID
         * @param destroy 是否销毁广告实例
         * @returns 是否成功移除
         */
        static removeCustomAd(adUnitId, destroy = true) {
            let inst = this.customAdMap.get(adUnitId);
            if (!inst)
                return false;
            if (destroy) {
                inst.destroy();
            }
            this.customAdMap.delete(adUnitId);
            return true;
        }
        /**
         * 获取插屏广告实例
         * @param opt 广告配置选项
         * @returns 插屏广告实例
         */
        static getInterstitialAd(opt) {
            const { adUnitId } = opt;
            if (!adUnitId) {
                console.warn("adUnitId is required  获取插屏广告失败");
                return null;
            }
            let inst = this.interstitialAdMap.get(adUnitId);
            if (inst) {
                return inst;
            }
            inst = new Guyu.WXInterstitialAd();
            this.interstitialAdMap.set(adUnitId, inst);
            inst.init(opt);
            return inst;
        }
        /**
         * 移除插屏广告
         * @param adUnitId 广告单元ID
         * @param destroy 是否销毁广告实例
         * @returns 是否成功移除
         */
        static removeInterstitialAd(adUnitId, destroy = true) {
            let inst = this.interstitialAdMap.get(adUnitId);
            if (!inst)
                return false;
            if (destroy) {
                inst.destroy();
            }
            this.interstitialAdMap.delete(adUnitId);
            return true;
        }
    }
    AdFactory.adMap = new Map();
    AdFactory.customAdMap = new Map();
    AdFactory.interstitialAdMap = new Map();
    Guyu.AdFactory = AdFactory;
})(Guyu);

(function (Guyu) {
    const ADError = {
        1000: "后端接口调用失败,请稍后再试",
        1001: "参数错误",
        1002: "广告单元无效",
        1003: "内部错误,请稍后再试",
        1004: "无合适广告,建议重启小游戏再试",
        1005: "广告组件审核中",
        1006: "广告组件被驳回",
        1007: "广告组件被封禁",
        1008: "广告单元已关闭",
    };
    class WXAdapter {
        constructor() {
            this._appId = null;
            /**
             * 小游戏界面交互api
             *
             * @type {IUserInterfaceAdapter}
             * @memberof WXAdapter
             */
            this.ui = new WXUIAdapter();
            this.ad = new WXAdAdapter();
        }
        get windowInfo() {
            if (!this._windowInfo) {
                this._windowInfo = this.wx.getWindowInfo();
            }
            return this._windowInfo;
        }
        get onMe() {
            //@ts-ignore
            let res = typeof wx !== 'undefined';
            return res;
        }
        get wx() {
            //@ts-ignore
            return wx;
        }
        ;
        get appId() {
            if (!this._appId) {
                let info = this.wx.getAccountInfoSync();
                this._appId = info.miniProgram.appId;
            }
            return this._appId;
        }
    }
    Guyu.WXAdapter = WXAdapter;
    class WXAdAdapter {
        constructor() {
            this.rewardedVideoAd = null;
            this.adLoadError = false;
            this.adErrorCode = 0;
            this.adErrorReason = "";
            this.adUnitId = "";
        }
        get wx() {
            //@ts-ignore
            return wx;
        }
        destroy() {
            if (this.rewardedVideoAd && this.rewardedVideoAd.destroy) {
                this.rewardedVideoAd.destroy();
            }
        }
        init(opt) {
            let { adUnitId, disableFallbackSharePage } = opt;
            if (disableFallbackSharePage == void 0) {
                disableFallbackSharePage = false;
                opt.disableFallbackSharePage = false;
            }
            Guyu.Log.warn(`创建激励视频广告 参数:${JSON.stringify(opt)}`);
            this.adUnitId = adUnitId;
            // 创建激励视频广告全局实例，提前初始化
            this.rewardedVideoAd = this.wx.createRewardedVideoAd({
                adUnitId: adUnitId,
                disableFallbackSharePage: opt.disableFallbackSharePage,
                multiton: true,
            });
            this.rewardedVideoAd.onError((err) => {
                this.adErrorCode = err.errCode;
                this.adLoadError = true;
                this.adErrorReason = err.errMsg + "(" + err.errCode + ")";
                console.error('激励视频 广告显示失败', err);
                let msg = err.errMsg;
                if (err.errCode) {
                    msg = `${msg}(${err.errCode})`;
                }
            });
        }
        playAd(opt) {
            if (!this.rewardedVideoAd) {
                return Promise.resolve({
                    success: false,
                    errMsg: "广告未初始化",
                });
            }
            let { showLoading, showError, onAdShow } = opt;
            if (this.adLoadError) {
                if (showError) {
                    let errMsg = ADError[this.adErrorCode] || `广告加载失败请稍后再试`;
                    let msg = `${errMsg}`;
                    if (this.adErrorCode) {
                        msg = `${errMsg}(${this.adErrorCode})`;
                    }
                    this.wx.showModal({ content: msg, showCancel: false });
                }
                return Promise.resolve({
                    success: false,
                    errMsg: "广告加载失败",
                });
            }
            return new Promise(async (resolve) => {
                this.resolve = resolve;
                if (showLoading) {
                    this.wx.showLoading({
                        title: '广告加载中...',
                    });
                }
                try {
                    await this.rewardedVideoAd.load();
                }
                catch (e) {
                    if (showLoading) {
                        this.wx.hideLoading();
                    }
                    Guyu.Log.error(`${this.adUnitId} rewardedVideoAd.load 广告加载失败`, e);
                    return resolve({
                        success: false,
                        errMsg: "广告加载失败,请稍后再试",
                    });
                }
                //广告显示成功
                this.rewardedVideoAd.offClose(this.onAdClose.bind(this));
                this.rewardedVideoAd.onClose(this.onAdClose.bind(this));
                this.rewardedVideoAd.show()
                    .catch(() => {
                    this.rewardedVideoAd.load();
                    if (showLoading) {
                        this.wx.hideLoading();
                    }
                    return resolve({
                        success: false,
                        errMsg: "广告未就绪,请稍后再试",
                    });
                }).then(() => {
                    if (onAdShow) {
                        onAdShow();
                    }
                    //广告展示成功
                    if (showLoading) {
                        this.wx.hideLoading();
                    }
                });
            });
        }
        onAdClose(res) {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发游戏奖励
                return this.resolve({
                    success: true,
                    errMsg: "播放成功",
                });
            }
            else {
                // 播放中途退出，不下发游戏奖励
                return this.resolve({
                    success: false,
                    errMsg: "播放中途退出，不下发游戏奖励",
                });
            }
        }
    }
    Guyu.WXAdAdapter = WXAdAdapter;
    class WXUIAdapter {
        get platObj() {
            //@ts-ignore
            return wx;
        }
        ;
        showToast(msg) {
            this.platObj.showToast({
                title: msg,
                icon: 'none',
                duration: 2000
            });
        }
        showAlert(msg) {
            this.platObj.showModal({
                title: '提示',
                content: msg,
                showCancel: false
            });
        }
        showLoading(msg) {
            this.platObj.showLoading({
                title: msg,
                mask: true
            });
        }
        hideLoading() {
            this.platObj.hideLoading();
        }
    }
    Guyu.WXUIAdapter = WXUIAdapter;
    //原生模板广告组件 https://developers.weixin.qq.com/minigame/dev/api/ad/CustomAd.html   
    class WXCustomAd {
        get wx() {
            //@ts-ignore
            return wx;
        }
        ;
        get ad() {
            return this._ad;
        }
        init(opt) {
            if (this._ad) {
                Guyu.Log.error("CustomAd 已经初始化 请勿重复初始化");
                return;
            }
            Guyu.Log.error(`开始初始化CustomAd广告 opt:`, opt);
            this._ad = this.wx.createCustomAd(opt);
            this._ad.onError((err) => {
                let tmp = opt;
                console.error('CustomAd广告 onError', err, tmp);
            });
        }
        show(style) {
            if (!this.ad) {
                Guyu.Log.error("CustomAd广告 未初始化 请先调用init");
                return;
            }
            if (style) {
                let windowInfo = Guyu.AdapterManager.adapter.windowInfo;
                this.ad.style.left = style.left || 0;
                this.ad.style.top = style.top || windowInfo.screenHeight - 150;
                this.ad.style.width = style.width || windowInfo.windowWidth;
                if (style.fixed != void 0) {
                    this.ad.style.fixed = style.fixed;
                }
            }
            this.ad.show().then(res => {
                Guyu.Log.warn(`CustomAd广告显示成功` + JSON.stringify(res));
            }).catch(e => {
                Guyu.Log.error(`CustomAd广告显示失败` + `${JSON.stringify(e)}`);
            });
            
        }
        hide() {
            if (!this.ad) {
                Guyu.Log.error("CustomAd 未初始化 请先调用init");
                return;
            }
            // debugger
            this.ad.hide();
        }
        destroy() {
            if (!this.ad) {
                Guyu.Log.warn("CustomAd 未初始化 无需销毁");
                return;
            }
            this.ad.destroy();
            this._ad = null;
        }
    }
    Guyu.WXCustomAd = WXCustomAd;
    //插屏广告   https://developers.weixin.qq.com/minigame/dev/api/ad/InterstitialAd.show.html
    class WXInterstitialAd {
        get wx() {
            //@ts-ignore
            return wx;
        }
        ;
        get ad() {
            return this._ad;
        }
        init(opt) {
            if (this._ad) {
                Guyu.Log.error("插屏广告 已经初始化 请勿重复初始化");
                return;
            }
            Guyu.Log.error(`开始初始化插屏广告 opt:`, opt);
            this._ad = this.wx.createInterstitialAd(opt);
            this._ad.onError((err) => {
                let tmp = opt;
                console.error('插屏广告  onError', err, tmp);
            });
        }
        show(f) {
            if (!this.ad) {
                Guyu.Log.error("插屏广告  未初始化 请先调用init");
                return;
            }
            this.ad.show().then(res => {
                Guyu.Log.warn(`插屏广告 广告显示成功` + JSON.stringify(res));
            }).catch(e => {
                Guyu.Log.error(`插屏广告 广告显示失败` + `${JSON.stringify(e)}`);
            });
            this.ad.onClose(()=>{
                f()
            });
        }
        hide() {
            if (!this.ad) {
                Guyu.Log.error("插屏广告  未初始化 请先调用init");
                return;
            }
            Guyu.Log.warn("插屏广告  不支持hide");
            return;
            this.ad.hide();
        }
        destroy() {
            if (!this.ad) {
                Guyu.Log.warn("插屏广告  未初始化 无需销毁");
                return;
            }
            this.ad.destroy();
            this._ad = null;
        }
    }
    Guyu.WXInterstitialAd = WXInterstitialAd;
})(Guyu);

(function (Guyu) {
    const ADError = {
        0: "平台内部错误",
        1: "广告对象已关闭",
        2: "广告数据暂未准备好",
        3: "网络错误",
        4: "广告校验失败",
        5: "详情页正在展示",
        1006: "过早展示广告，需在规定时间后再展示广告"
    };
    class KSAdapter {
        constructor() {
            this._appId = null;
            /**
             * 小游戏界面交互api
             *
             * @type {IUserInterfaceAdapter}
             * @memberof KSAdapter
             */
            this.ui = new KSUIAdapter();
            this.ad = new KSADAdapeter();
        }
        get onMe() {
            //@ts-ignore
            let res = typeof KSGameGlobal !== 'undefined';
            return res;
        }
        get wx() {
            //@ts-ignore
            return wx;
        }
        get appId() {
            if (!this._appId) {
                let info = this.wx.getAccountInfoSync();
                this._appId = info.miniProgram.appId;
            }
            return this._appId;
        }
    }
    Guyu.KSAdapter = KSAdapter;
    class KSADAdapeter {
        constructor() {
            this.rewardedVideoAd = null;
            this.adLoadError = false;
            this.adErrorCode = 0;
            this.adErrorReason = "";
            this.adUnitId = "";
        }
        get wx() {
            //@ts-ignore
            return wx;
        }
        ;
        destroy() {
            if (this.rewardedVideoAd && this.rewardedVideoAd.destroy) {
                this.destroy();
            }
        }
        init(opt) {
            let { adUnitId } = opt;
            this.adUnitId = adUnitId;
            // 创建激励视频广告全局实例，提前初始化
            this.rewardedVideoAd = this.wx.createRewardedVideoAd({
                adUnitId: adUnitId,
                multiton: true,
            });
            this.rewardedVideoAd.onError((err) => {
                this.adErrorCode = err.errCode;
                this.adLoadError = true;
                this.adErrorReason = err.errMsg + "(" + err.errCode + ")";
                console.error('激励视频 广告显示失败', err);
                let msg = err.errMsg;
                if (err.errCode) {
                    msg = `${msg}(${err.errCode})`;
                }
            });
        }
        playAd(opt) {
            let { showLoading, showError, onAdShow } = opt;
            if (this.adLoadError) {
                if (showError) {
                    let errMsg = ADError[this.adErrorCode] || `广告加载失败请稍后再试`;
                    let msg = `${errMsg}`;
                    if (this.adErrorCode) {
                        msg = `${errMsg}(${this.adErrorCode})`;
                    }
                    this.wx.showModal({ content: msg });
                }
                return Promise.resolve({
                    success: false,
                    errMsg: "广告加载失败",
                });
            }
            return new Promise(resolve => {
                this.resolve = resolve;
                if (showLoading) {
                    this.wx.showLoading({
                        title: '广告加载中...',
                    });
                    if (onAdShow) {
                        onAdShow();
                    }
                }
                //广告显示成功
                this.rewardedVideoAd.offClose(null);
                this.rewardedVideoAd.onClose(this.onAdClose.bind(this));
                this.rewardedVideoAd.show()
                    .catch(() => {
                    this.rewardedVideoAd.load();
                    if (showLoading) {
                        this.wx.hideLoading();
                    }
                    return resolve({
                        success: false,
                        errMsg: "广告未就绪,请稍后再试",
                    });
                }).then(() => {
                    //广告展示成功
                    if (showLoading) {
                        this.wx.hideLoading();
                    }
                });
            });
        }
        onAdClose(res) {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发游戏奖励
                return this.resolve({
                    success: true,
                    errMsg: "播放成功",
                });
            }
            else {
                // 播放中途退出，不下发游戏奖励
                return this.resolve({
                    success: false,
                    errMsg: "播放中途退出，不下发游戏奖励",
                });
            }
        }
    }
    Guyu.KSADAdapeter = KSADAdapeter;
    class KSUIAdapter {
        get platObj() {
            //@ts-ignore
            return ks;
        }
        showToast(msg) {
            this.platObj.showToast({
                title: msg,
                duration: 2000
            });
        }
        showAlert(msg) {
            this.platObj.showModal({
                title: '提示',
                content: msg,
                showCancel: false
            });
        }
        showLoading(msg) {
            this.platObj.showLoading({
                title: msg
            });
        }
        hideLoading() {
            this.platObj.hideLoading();
        }
    }
    Guyu.KSUIAdapter = KSUIAdapter;
})(Guyu);

(function (Guyu) {
    class Tools {
        static wait(ms) {
            return new Promise(_ => {
                setTimeout(() => {
                    return _();
                }, ms);
            });
        }
        static secondsToCountdown(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            let res = `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
            return res;
        }
    }
    Guyu.Tools = Tools;
})(Guyu);

(function (Guyu) {
    function checkPhoneNum(num) {
        if (!num)
            return false;
        // 1--以1为开头；
        // 2--第二位可为2,3,4,5,6,7,8,9中的任意一位；
        // 3--最后以0-9的9个整数结尾。
        let reg = /^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$/;
        new Guyu.TestAAA();
        return reg.test(num.toString());
    }
    Guyu.checkPhoneNum = checkPhoneNum;
})(Guyu);

(function (Guyu) {
    // ** 日志等级 */
    let LogLevel;
    (function (LogLevel) {
        LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
        LogLevel[LogLevel["INFO"] = 1] = "INFO";
        LogLevel[LogLevel["WARN"] = 2] = "WARN";
        LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
        LogLevel[LogLevel["NONE"] = 4] = "NONE";
    })(LogLevel = Guyu.LogLevel || (Guyu.LogLevel = {}));
    /**
     * 通用日志类
     */
    class Log {
        /**
         * 设置日志等级
         * @param level 日志等级
         */
        static setLevel(level) {
            Log.config.level = level;
        }
        static log(level, ...args) {
            if (level < Log.config.level)
                return;
            if (level == LogLevel.WARN) {
                console.warn(...args);
            }
            else if (level == LogLevel.ERROR) {
                console.error(...args);
            }
            else {
                console.log(...args);
            }
        }
        /**
         * 调试日志
         * @param title 标题
         * @param msg 信息
         */
        static debug(...args) {
            Log.log(LogLevel.DEBUG, ...args);
        }
        /**
         * 信息日志
         * @param title 标题
         * @param msg 信息
         */
        static info(...args) {
            Log.log(LogLevel.INFO, ...args);
        }
        /**
         * 警告日志
         * @param title 标题
         * @param msg 信息
         */
        static warn(...args) {
            Log.log(LogLevel.WARN, ...args);
        }
        /**
         * 错误日志
         * @param title 标题
         * @param msg 信息
         */
        static error(...args) {
            Log.log(LogLevel.ERROR, ...args);
        }
    }
    Log.config = {
        level: LogLevel.DEBUG,
    };
    Guyu.Log = Log;
})(Guyu);

(function (Guyu) {
    /**
     * Day类 - 提供完整的日期操作功能
     */
    class DayLite {
        constructor(date) {
            if (typeof date === 'number' && date < 10000000000) {
                // 如果是秒级时间戳，转换为毫秒级
                this.date = new Date(date * 1000);
            }
            else {
                this.date = date ? new Date(date) : new Date();
            }
        }
        /**
         * 创建DayLite实例
         * @param date 日期参数
         */
        static create(date) {
            return new DayLite(date);
        }
        /**
         * 获取当前时间的Day实例
         */
        static now() {
            return new DayLite();
        }
        /**
         * 克隆当前实例
         */
        clone() {
            return new DayLite(this.date);
        }
        /**
         * 格式化日期
         * @param template 格式模板
         */
        format(template = 'YYYY-MM-DDTHH:mm:ss.SSSZ') {
            const year = this.date.getFullYear();
            const month = this.date.getMonth() + 1;
            const day = this.date.getDate();
            const hour = this.date.getHours();
            const minute = this.date.getMinutes();
            const second = this.date.getSeconds();
            const millisecond = this.date.getMilliseconds();
            const offset = -this.date.getTimezoneOffset();
            const offsetHours = Math.abs(Math.floor(offset / 60));
            const offsetMinutes = Math.abs(offset % 60);
            return template
                .replace(/[Yy]{4}|yyyy/, year.toString())
                .replace(/[Mm]{2}|MM/, month.toString().padStart(2, '0'))
                .replace(/[Dd]{2}|dd/, day.toString().padStart(2, '0'))
                .replace(/[Hh]{2}|HH/, hour.toString().padStart(2, '0'))
                .replace(/mm/, minute.toString().padStart(2, '0'))
                .replace(/ss/, second.toString().padStart(2, '0'))
                .replace(/[Ss]{3}|SSS/, millisecond.toString().padStart(3, '0'))
                .replace(/Z/, `${offset >= 0 ? '+' : '-'}${offsetHours.toString().padStart(2, '0')}:${offsetMinutes.toString().padStart(2, '0')}`);
        }
        /**
         * 获取年份
         */
        getYear() {
            return this.date.getFullYear();
        }
        /**
         * 设置年份
         * @param value 年份值
         */
        setYear(value) {
            const newDate = new Date(this.date);
            newDate.setFullYear(value);
            return new DayLite(newDate);
        }
        /**
         * 获取月份 (0-11)
         */
        getMonth() {
            return this.date.getMonth();
        }
        /**
         * 设置月份 (0-11)
         * @param value 月份值
         */
        setMonth(value) {
            const newDate = new Date(this.date);
            newDate.setMonth(value);
            return new DayLite(newDate);
        }
        /**
         * 获取日期
         */
        getDate() {
            return this.date.getDate();
        }
        /**
         * 设置日期
         * @param value 日期值
         */
        setDate(value) {
            const newDate = new Date(this.date);
            newDate.setDate(value);
            return new DayLite(newDate);
        }
        /**
         * 获取星期几 (0-6, 0为星期日)
         */
        getDay() {
            return this.date.getDay();
        }
        /**
         * 获取小时
         */
        getHour() {
            return this.date.getHours();
        }
        /**
         * 设置小时
         * @param value 小时值 (0-23)
         */
        setHour(value) {
            const newDate = new Date(this.date);
            newDate.setHours(value);
            return new DayLite(newDate);
        }
        /**
         * 获取分钟
         */
        getMinute() {
            return this.date.getMinutes();
        }
        /**
         * 设置分钟
         * @param value 分钟值 (0-59)
         */
        setMinute(value) {
            const newDate = new Date(this.date);
            newDate.setMinutes(value);
            return new DayLite(newDate);
        }
        /**
         * 获取秒数
         */
        getSecond() {
            return this.date.getSeconds();
        }
        /**
         * 设置秒数
         * @param value 秒数值 (0-59)
         */
        setSecond(value) {
            const newDate = new Date(this.date);
            newDate.setSeconds(value);
            return new DayLite(newDate);
        }
        /**
         * 获取毫秒数
         */
        getMillisecond() {
            return this.date.getMilliseconds();
        }
        /**
         * 设置毫秒数
         * @param value 毫秒数值 (0-999)
         */
        setMillisecond(value) {
            const newDate = new Date(this.date);
            newDate.setMilliseconds(value);
            return new DayLite(newDate);
        }
        /**
         * 增加指定时间
         * @param value 增加的数值
         * @param unit 时间单位
         */
        add(value, unit = 'millisecond') {
            const newDate = new Date(this.date);
            switch (unit) {
                case 'year':
                    newDate.setFullYear(newDate.getFullYear() + value);
                    break;
                case 'month':
                    newDate.setMonth(newDate.getMonth() + value);
                    break;
                case 'day':
                    newDate.setDate(newDate.getDate() + value);
                    break;
                case 'hour':
                    newDate.setHours(newDate.getHours() + value);
                    break;
                case 'minute':
                    newDate.setMinutes(newDate.getMinutes() + value);
                    break;
                case 'second':
                    newDate.setSeconds(newDate.getSeconds() + value);
                    break;
                case 'millisecond':
                    newDate.setMilliseconds(newDate.getMilliseconds() + value);
                    break;
            }
            return new DayLite(newDate);
        }
        /**
         * 减少指定时间
         * @param value 减少的数值
         * @param unit 时间单位
         */
        subtract(value, unit) {
            return this.add(-value, unit);
        }
        /**
         * 获取时间戳（毫秒）
         */
        valueOf() {
            return this.date.getTime();
        }
        /**
         * 转换为Date对象
         */
        toDate() {
            return new Date(this.date);
        }
        /**
         * 转换为ISO字符串
         */
        toISOString() {
            return this.date.toISOString();
        }
        /**
         * 判断是否为有效日期
         */
        isValid() {
            return !isNaN(this.date.getTime());
        }
        /**
         * 判断是否在指定日期之前
         * @param date 比较的日期
         * @param unit 比较的时间单位
         */
        isBefore(date, unit) {
            const compareDate = date instanceof DayLite ? date : new DayLite(date);
            if (!unit)
                return this.valueOf() < compareDate.valueOf();
            switch (unit) {
                case 'year':
                    return this.getYear() < compareDate.getYear();
                case 'month':
                    return this.getYear() < compareDate.getYear() ||
                        (this.getYear() === compareDate.getYear() && this.getMonth() < compareDate.getMonth());
                case 'day':
                    return this.startOf('day').valueOf() < compareDate.startOf('day').valueOf();
                case 'hour':
                    return this.startOf('hour').valueOf() < compareDate.startOf('hour').valueOf();
                case 'minute':
                    return this.startOf('minute').valueOf() < compareDate.startOf('minute').valueOf();
                case 'second':
                    return this.startOf('second').valueOf() < compareDate.startOf('second').valueOf();
                default:
                    return this.valueOf() < compareDate.valueOf();
            }
        }
        /**
         * 判断是否在指定日期之后
         * @param date 比较的日期
         * @param unit 比较的时间单位
         */
        isAfter(date, unit) {
            const compareDate = date instanceof DayLite ? date : new DayLite(date);
            if (!unit)
                return this.valueOf() > compareDate.valueOf();
            return !this.isBefore(date, unit) && !this.isSame(date, unit);
        }
        /**
         * 判断是否与指定日期相同
         * @param date 比较的日期
         * @param unit 比较的时间单位
         */
        isSame(date, unit) {
            const compareDate = date instanceof DayLite ? date : new DayLite(date);
            if (!unit)
                return this.valueOf() === compareDate.valueOf();
            return this.startOf(unit).valueOf() === compareDate.startOf(unit).valueOf();
        }
        /**
         * 获取两个日期之间的差值
         * @param date 比较的日期
         * @param unit 比较的时间单位
         */
        diff(date, unit = 'millisecond') {
            const compareDate = date instanceof DayLite ? date : new DayLite(date || new Date());
            const diff = this.valueOf() - compareDate.valueOf();
            switch (unit) {
                case 'year':
                    return this.getYear() - compareDate.getYear();
                case 'month':
                    return (this.getYear() - compareDate.getYear()) * 12 + (this.getMonth() - compareDate.getMonth());
                case 'day':
                    return Math.floor(diff / (1000 * 60 * 60 * 24));
                case 'hour':
                    return Math.floor(diff / (1000 * 60 * 60));
                case 'minute':
                    return Math.floor(diff / (1000 * 60));
                case 'second':
                    return Math.floor(diff / 1000);
                default:
                    return diff;
            }
        }
        /**
         * 获取当月天数
         */
        daysInMonth() {
            return new Date(this.getYear(), this.getMonth() + 1, 0).getDate();
        }
        /**
         * 设置为当前时间单位的开始
         * @param unit 时间单位
         */
        startOf(unit) {
            const newDate = new Date(this.date);
            switch (unit) {
                case 'year':
                    newDate.setMonth(0, 1);
                    newDate.setHours(0, 0, 0, 0);
                    break;
                case 'month':
                    newDate.setDate(1);
                    newDate.setHours(0, 0, 0, 0);
                    break;
                case 'day':
                    newDate.setHours(0, 0, 0, 0);
                    break;
                case 'hour':
                    newDate.setMinutes(0, 0, 0);
                    break;
                case 'minute':
                    newDate.setSeconds(0, 0);
                    break;
                case 'second':
                    newDate.setMilliseconds(0);
                    break;
            }
            return new DayLite(newDate);
        }
        /**
         * 设置为当前时间单位的结束
         * @param unit 时间单位
         */
        endOf(unit) {
            const newDate = new Date(this.date);
            switch (unit) {
                case 'year':
                    newDate.setMonth(11, 31);
                    newDate.setHours(23, 59, 59, 999);
                    break;
                case 'month':
                    newDate.setDate(this.daysInMonth());
                    newDate.setHours(23, 59, 59, 999);
                    break;
                case 'day':
                    newDate.setHours(23, 59, 59, 999);
                    break;
                case 'hour':
                    newDate.setMinutes(59, 59, 999);
                    break;
                case 'minute':
                    newDate.setSeconds(59, 999);
                    break;
                case 'second':
                    newDate.setMilliseconds(999);
                    break;
            }
            return new DayLite(newDate);
        }
    }
    Guyu.DayLite = DayLite;
})(Guyu);

(function (Guyu) {
    class Http {
        /** 设置日志开关 */
        static setLogEnabled(enabled) {
            this.enableLog = enabled;
        }
        static LOG(...args) {
            if (this.enableLog) {
                Guyu.Log.debug(args[0], args.length > 1 ? args.slice(1).join(' ') : undefined);
            }
        }
        static get(url, queryParams, headers) {
            const startTime = Date.now();
            if (queryParams) {
                let queryString = '';
                const keys = Object.keys(queryParams);
                for (let i = 0; i < keys.length; i++) {
                    const key = keys[i];
                    const value = queryParams[key];
                    if (i > 0) {
                        queryString += '&';
                    }
                    queryString += `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
                }
                if (url.includes('?')) {
                    url += '&' + queryString;
                }
                else {
                    url += '?' + queryString;
                }
            }
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', url, true);
                xhr.timeout = 10000;
                // 合并请求头
                const mergedHeaders = Object.assign({}, this.defaultHeaders, headers);
                const headerKeys = Object.keys(mergedHeaders);
                for (let i = 0; i < headerKeys.length; i++) {
                    const key = headerKeys[i];
                    const value = mergedHeaders[key];
                    xhr.setRequestHeader(key, value);
                }
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 400) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                const endTime = Date.now();
                                this.LOG(`耗时: ${endTime - startTime}ms`, `GET ${url} RESPONSE: ${JSON.stringify(response)}`);
                                resolve(response);
                            }
                            catch (e) {
                                const errMsg = `JSON解析失败: ${e.message}`;
                                Guyu.Log.error('HTTP请求错误', errMsg);
                                reject(new Error(errMsg));
                            }
                        }
                        else {
                            const errMsg = `请求失败: ${xhr.status} ${xhr.statusText}`;
                            Guyu.Log.error('HTTP请求错误', errMsg);
                            reject(new Error(errMsg));
                        }
                    }
                };
                xhr.ontimeout = () => {
                    Guyu.Log.error('HTTP请求错误', '请求超时');
                    reject(new Error('请求超时'));
                };
                xhr.onerror = () => {
                    Guyu.Log.error('HTTP请求错误', '网络错误');
                    reject(new Error('网络错误'));
                };
                xhr.send();
            });
        }
        static post(url, data, headers) {
            const startTime = Date.now();
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('POST', url, true);
                xhr.timeout = 10000;
                // 合并请求头
                const mergedHeaders = Object.assign({}, this.defaultHeaders, headers);
                const keys = Object.keys(mergedHeaders);
                for (let i = 0; i < keys.length; i++) {
                    const key = keys[i];
                    const value = mergedHeaders[key];
                    xhr.setRequestHeader(key, value);
                }
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 400) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                const endTime = Date.now();
                                this.LOG(`耗时: ${endTime - startTime}ms`, `POST ${url} RESPONSE: ${JSON.stringify(response)}`);
                                resolve(response);
                            }
                            catch (e) {
                                const errMsg = `JSON解析失败: ${e.message}`;
                                Guyu.Log.error('HTTP请求错误', errMsg);
                                reject(new Error(errMsg));
                            }
                        }
                        else {
                            const errMsg = `请求失败: ${xhr.status} ${xhr.statusText}`;
                            Guyu.Log.error('HTTP请求错误', errMsg);
                            reject(new Error(errMsg));
                        }
                    }
                };
                xhr.ontimeout = () => {
                    Guyu.Log.error('HTTP请求错误', '请求超时');
                    reject(new Error('请求超时'));
                };
                xhr.onerror = () => {
                    Guyu.Log.error('HTTP请求错误', '网络错误');
                    reject(new Error('网络错误'));
                };
                xhr.send(JSON.stringify(data));
            });
        }
    }
    /** 是否启用日志输出 */
    Http.enableLog = true;
    Http.defaultHeaders = {
        'Content-Type': 'application/json'
    };
    Guyu.Http = Http;
})(Guyu);

(function (Guyu) {
    class TestAAA {
        aaa() {
            Guyu.Log.debug('aaa');
            return 123;
        }
    }
    Guyu.TestAAA = TestAAA;
})(Guyu);
